package com.seashop.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.seashop.config.PropertiesConfig;
import com.seashop.constant.AliOSSConstant;
import com.seashop.enums.ActiveProfileEnum;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * @author moredln
 * @desc 上传OSS工具
 * @date 11/24/20 11:30 PM
 */
public class OSSUploadUtil {

    /***
     * 上传图片到OSS服务
     * @param multipartFile
     * @param folderName: 上传文件存放的文件夹名称,可选
     * @return 图片存储返回的url
     */
    public static String uploadImage(MultipartFile multipartFile, String folderName) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = AliOSSConstant.OUTER_URL;

        String runtime = PropertiesConfig.getActiveProfile();
        // 开发生产走阿里云内网
        if (ActiveProfileEnum.DEV.getName().equals(runtime) || ActiveProfileEnum.PROD.getName().equals(runtime)) {
            endpoint = AliOSSConstant.INNER_URL;
        }
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = AliOSSConstant.ACCESS_KEY_ID;

        String accessKeySecret = AliOSSConstant.ACCESS_KEY_SECRET;
        // 创建OSS实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // seashop项目固定这个bucketname
        String bucketName = AliOSSConstant.BUCKET_NAME;
        // 文件命名必须保证不能重名,否则覆盖
        Date date = new Date();
        String originalFileName = multipartFile.getOriginalFilename();
        String[] list = originalFileName.split("\\.");
        String objectName = date.getTime() + "." + list[list.length - 1];
        if (folderName != null || folderName.length() > 0) {
            // 创建虚拟的文件夹
            objectName = folderName + "/" + objectName;
        }
        // 创建上传Object的Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(multipartFile.getSize());
//        objectMetadata.setCacheControl("no-cache");
//        objectMetadata.setHeader("Pragma", "no-cache");
//        String contentType = multipartFile.getContentType();
//        objectMetadata.setContentType(contentType);
        String contentType = "image/jpeg";
        if (originalFileName.endsWith(".gif")) {
            contentType = "image/gif";
        } else if (originalFileName.endsWith(".bmp")) {
            contentType = "image/bmp";
        } else if (originalFileName.endsWith(".webp")) {
            contentType = "image/webp";
        }
        objectMetadata.setContentType(contentType);
        objectMetadata.setContentEncoding("utf-8");
        objectMetadata.setContentDisposition("inline;filename=" + objectName);
        objectMetadata.addUserMetadata("from", "imagesearch");

        PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
        // 必须关闭OSSClient
        ossClient.shutdown();

        if (result.getETag() != null) {
            // 内网url "https://" + bucketName + ".oss-ap-southeast-1-internal.aliyuncs.com/" + objectName;
            // 外网url "https://" + bucketName + ".oss-ap-southeast-1.aliyuncs.com/" + objectName;
            // CDN加速url
            String imgUrl = "https://os.aopcdn.com/" + objectName;
            return imgUrl;
        }
        return null;
    }

}
